﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CPF;
using CPF.Controls;
using OpenCvSharp;

namespace DesktopCam
{
    internal class OpenCVFunc
    {

        public static async void LogOut(TextBox logout, CancellationToken token)
        {

            while (!token.IsCancellationRequested)
            {
                token.ThrowIfCancellationRequested();
                logout.Invoke(() => logout.AppentText("."));
                await Task.Delay(1000);
            }
        }

        static VideoCapture capture;

        public static async void OpenCam(Picture cameraPicture, CancellationToken token)
        {// 创建VideoCapture对象，默认的摄像头索引是0
             capture = new VideoCapture(0);
            //VideoCapture capture2 = new VideoCapture(0);
            if (!capture.IsOpened())
            {
                MessageBox.Show("无法打开摄像头");
                return;
            }

            //int sleepTime = (int)Math.Round(1000 / capture.Fps);
            using Mat image = new Mat();
            while (!token.IsCancellationRequested)
            {
                // 从摄像头读取一帧
                capture?.Read(image);

                // 如果读取到的帧为空，表示没有更多的帧可以读取
                if (image.Empty())
                {
                    MessageBox.Show("No signal");
                    break;
                }
                // 在窗口中显示帧
                cameraPicture.Source = image.ToMemoryStream();
                await Task.Delay(40);  //1000/24

            }

            cameraPicture.Source = "res://CamCpf/57f38960a5aa4.png";
        }

        public static void CloseCam()
        {
            //using var capture = new VideoCapture(0);
            //if (!capture.IsOpened())
            //{
            //    MessageBox.Show("无法打开摄像头");
            //}
            capture?.Release();
            if(capture != null )
            {
                MessageBox.Show($"null:{capture==null}    open:{capture.IsOpened()}");
                //capture.Open(0);
                //MessageBox.Show($"null:{capture == null}    open:{capture.IsOpened()}");

            }
            else
            {
                MessageBox.Show("null");
            }
            return;
        }



    
    }
}
